package alipay.openplatform.edu.campus.jiuye.api.filter;

import alipay.openplatform.edu.campus.jiuye.api.constant.Constant;
import alipay.openplatform.edu.campus.jiuye.common.enums.ResultCode;
import alipay.openplatform.edu.campus.jiuye.model.po.UserAdmin;
import alipay.openplatform.edu.campus.jiuye.service.dao.ApiResult;
import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * admin 权限过滤
 *
 * @author zhz
 * @create 2016-08-25
 */
public class AdminFilter implements Filter {

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(true);

//        response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域
        UserAdmin userAdmin = (UserAdmin) session.getAttribute(Constant.USER_ADMIN);//登录人
        String url = request.getRequestURI();
        if (userAdmin == null) {
            //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
            if (url != null && !url.equals("") && (url.indexOf("login") < 0 && url.indexOf("getImageCode") < 0 && url.indexOf("index")<0 )) {
                response.getWriter().write(JSON.toJSONString(new ApiResult().build(ResultCode.AUTH_UNAUTHORIZED.getCode(),ResultCode.AUTH_UNAUTHORIZED.getName())));
                response.getWriter().flush();
                return;
            }

        }
        chain.doFilter(req, res);
        return;

    }

    public void init(FilterConfig config) throws ServletException {
    }

}
